package com.nowoe.mvc.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nowoe.mvc.annotation.Controller;
import com.nowoe.mvc.annotation.RequestMapping;
import com.nowoe.mvc.annotation.RequestParam;
import com.nowoe.mvc.annotation.ResponseBody;
import com.nowoe.mvc.context.WebApplicationContext;
import com.nowoe.mvc.exception.ContextException;
import com.nowoe.mvc.handler.RequestHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 倚栏听风 2023/9/15 11:02
 */
public class DispatchServlet extends HttpServlet {
    private WebApplicationContext applicationContext;
    private List<RequestHandler> handlerList = new ArrayList<>();

    @Override
    public void init() throws ServletException {
        //读取配置文件 classpath:applicationContext.xml
        String configPath = this.getInitParameter("contextConfigLocation");
        //创建Spring容器
        applicationContext = new WebApplicationContext(configPath);
        //初始化容器
        applicationContext.refresh();
        //初始化映射请求
        initHandlerMapping();
        handlerList.forEach(item -> System.out.println("映射请求：" + item.getUrl()));

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理请求
        executeDispatch(req, resp);
    }


    /**
     * 初始化映射请求
     */
    private void initHandlerMapping() {
        if (applicationContext.getBeanFactory().getClassMap().isEmpty()) {
            throw new ContextException("Ioc 容器为空");
        }
        for (Map.Entry<Class<?>, Object> entry : applicationContext.getBeanFactory().getClassMap().entrySet()) {
            Class<?> aClass = entry.getKey();
            if (aClass.isAnnotationPresent(Controller.class)) {
                Method[] methods = aClass.getMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(RequestMapping.class)) {
                        RequestMapping annotation = method.getAnnotation(RequestMapping.class);
                        String url = annotation.value();
                        RequestHandler requestHandler = new RequestHandler(url, entry.getValue(), method);
                        handlerList.add(requestHandler);
                    }
                }
            }

        }
    }

    /**
     * //处理请求
     *
     * @param req
     * @param resp
     */
    private void executeDispatch(HttpServletRequest req, HttpServletResponse resp) {
        RequestHandler handler = getHandler(req);
        try {
            if (handler == null) {
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().print("<h1> 404 Not Found <h1>");
            } else {
                Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
                Object[] objects = new Object[parameterTypes.length];
                for (int i = 0; i < parameterTypes.length; i++) {
                    Class<?> parameterType = parameterTypes[i];
                    if ("HttpServletRequest".equals(parameterType.getSimpleName())) {
                        objects[i] = req;
                    } else if ("HttpServletResponse".equals(parameterType.getSimpleName())) {
                        objects[i] = resp;
                    }
                }
                Map<String, String[]> parameterMap = req.getParameterMap();
                for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue()[0];
                    //判断参数注解
                    int index = hasRequestParam(handler.getMethod(), key);
                    if (index != -1) {
                        objects[index] = Integer.parseInt(value);
                    } else {
                        List<String> parameterNames = getParameterNames(handler.getMethod());
                        for (String parameterName : parameterNames) {
                            if (parameterName.equals(key)) {
                                objects[parameterNames.indexOf(parameterName)] = Integer.parseInt(value);
                            }
                        }
                    }
                }
                Object res = handler.getMethod().invoke(handler.getController(), objects);
                if (res instanceof String) {
                    String value = (String) res;
                    if (value.contains(":")) {
                        String viewType = value.split(":")[0];
                        String viewTName = value.split(":")[1];
                        if ("forward".equals(viewType)) {
                            req.getRequestDispatcher(viewTName).forward(req, resp);
                        } else if ("redirect".equals(viewType)) {
                            resp.sendRedirect(viewTName);
                        }
                    } else {
                        //转发
                        req.getRequestDispatcher(value).forward(req, resp);
                    }
                } else {
                    //返回对象
                    Method method = handler.getMethod();
                    if (method.isAnnotationPresent(ResponseBody.class)) {
                        ObjectMapper objectMapper = new ObjectMapper();
                        String value = objectMapper.writeValueAsString(res);
                        resp.setContentType("text/html;charset=utf-8");
                        PrintWriter writer = resp.getWriter();
                        writer.write(value);
                        writer.flush();
                        writer.close();
                    }
                }

            }
        } catch (
                Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 判断参数是否有RequestParam注解
     *
     * @param method
     * @param name
     * @return
     */
    private int hasRequestParam(Method method, String name) {
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            if (parameter.isAnnotationPresent(RequestParam.class)) {
                RequestParam annotation = parameter.getAnnotation(RequestParam.class);
                String value = annotation.value();
                if (value.equals(name)) {
                    return i;
                }
            }
        }
        return -1;
    }

    private List<String> getParameterNames(Method method) {
        List<String> list = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (Parameter parameter : parameters) {
            list.add(parameter.getName());
        }
        return list;
    }

    private RequestHandler getHandler(HttpServletRequest req) {
        String uri = req.getRequestURI();
        for (RequestHandler handler : handlerList) {
            if (uri.equals(handler.getUrl())) {
                return handler;
            }
        }
        return null;
    }


}
